from django.shortcuts import render
from django.http import HttpResponse  # 从http模块中导入HttpResponse类
from app.models.cookbook import *
from app.models.delivery import *
from django.core.paginator import Paginator,PageNotAnInteger
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
import os,json
from app.cookbook.utils import *
# Create your views here.


def index(request):  # 定义站点首页视图函数
    return HttpResponse('test url')  # 后台管理首页


def get_menu_manage(request):
    """
    菜谱列表页
    :param request:page
    :return:菜谱列表
    """
    limit = 5  # 限制每一页显示的条目数量
    menu = CookBook.objects.order_by("-_id")
    paginator = Paginator(menu, limit)
    try:
        page_num = request.GET.get('page', 1)
    except PageNotAnInteger:
        page_num = 1
    loaded = paginator.page(page_num)

    context = {
        'cookbook': loaded
    }

    return render(request,'visites/menu.html',context)  #菜谱列表页


def get_menu_detail_manage(request):
    """
    菜谱详情页
    :param request:
    :return:
    """
    cookbook_id = request.GET['id']
    cookbook = CookBook.objects(id=cookbook_id)

    context = {
        'cookbook': cookbook
    }

    return render(request,'visites/menu-detail.html',context)  #菜谱详情页


def get_menu_add_manage(request):
    """
    添加菜谱页面
    :param request:
    :return:
    """
    communitylist = Community.objects.all()
    context = {}
    context["communityList"] = communitylist
    return render(request,'visites/add-menu.html',context)  #添加菜谱


@require_http_methods(["POST", "GET"])
@csrf_exempt
def insert_menu_manage(request):
    """
    新增菜谱
    :param request: cookbook
    :return: code
    """
    res = 0
    if request.is_ajax() and request.method == "POST":
        dataStr = request.body
        data = json.loads(dataStr)
        menuList = data['menu']
        foodList = []
        for i in range(len(menuList)):
            food = MenuFood(id=i, name=menuList[i]['name'], price=menuList[i]['price'],
                            remarks=menuList[i]['remarks'], image=menuList[i]['image'], status="Open")
            foodList.append(food)
        cookBook = CookBook(status='Open', banner=data['banner'], period_number=data['period_number'],
                            community_id=data['community_id'],community_name= data['community_name'], order_time=data['order_time'],
                            delivery_time=data['delivery_time'], hot_push=data['hot_push'], menu=foodList)
        cookBook.save()
        res = 1
    return HttpResponse(res)


def upload_avatar(request):
    """
    图片上传
    :param request: image
    :return: file_path
    """
    file_obj = request.FILES.get('avatar')
    ext = os.path.splitext(file_obj.name)[1]    # 获取文件格式
    new_name = tid_maker()+ext  # 按照时间重命名

    file_path = os.path.join('media/visites/image/cookbook/', new_name)
    with open(file_path, 'wb') as f:
        for chunk in file_obj.chunks():
            f.write(chunk)
    return HttpResponse(file_path)


@csrf_exempt
@require_http_methods(["POST", "GET"])
def update_cookbook_manage(request):
    """
    菜谱状态修改接口
    :param request:
    :return:
    """
    cookbook_id = request.POST.get('id')
    cookbook = CookBook.objects.get(id=cookbook_id)
    if cookbook.status =='Open':
        cookbook.status = 'Close'
    else:
        cookbook.status = 'Open'
    cookbook.save()
    return HttpResponse(1)


@csrf_exempt
@require_http_methods(["POST", "GET"])
def update_food_manage(request):
    """
    菜品状态修改接口
    :param request:
    :return:
    """
    code = 0
    cookbook_id = request.POST.get('id')
    food_id = int(request.POST.get('food_id'))
    if cookbook_id is None or food_id is None:
        code = -1
    else:
        cookbook = CookBook.objects.get(id=cookbook_id)
        foodList = cookbook.menu
        for food in foodList:
            if food.id == food_id:
                if food.status =='Open':
                    food.status = 'Close'
                else:
                    food.status = 'Open'
                cookbook.save()
                code = 1
    return HttpResponse(code)





